import re
import atexit
from bs4 import BeautifulSoup
from comm.functons import config
from comm.CacheManager import CacheManager
from comm.chromedriver import ChromeDriverService
from urllib import parse

from gua.Gua01ImgDecry import Gua01ImgDecry

atexit.register(ChromeDriverService.close_driver)


class Gua01:
    default_page = '/page/{}'

    def __init__(self):
        self.host = config('domain.gua_01')
        self.cache = CacheManager()
        self.img_down = Gua01ImgDecry()
        ChromeDriverService.http_get(self.host)

    def _down(self, path=''):
        url = self.host + path
        txt = self.cache.get(url)
        if txt:
            return BeautifulSoup(txt, 'lxml'), None

        driver = ChromeDriverService.http_get(url)
        txt = driver.page_source
        return BeautifulSoup(txt, 'lxml'), txt

    def nav(self):
        soup, txt = self._down()
        arr = soup.select_one('#navbarCollapse > ul.navbar-nav.mr-auto').find_all('a', class_='nav-link')
        data = []
        for i in arr:
            d = dict(title=i.text, id=i.get('href') + '{}')
            if 'category' in d['id']:
                data.append(d)
        data.insert(0, {'title': '首页', 'id': self.default_page})
        return data

    def list(self, path):
        soup, txt = self._down(path)
        arr = soup.select('#archive > article > a')  # 分类页
        if len(arr) <= 0:
            arr = soup.select('#index > article > a')  # 主页

        data = []
        for i in arr:
            tim = i.select_one('div.post-card-mask > div > div > span:nth-child(2)')
            if not tim:
                continue
            tit = i.find('h2', class_='post-card-title').text.replace('热搜 HOT', '').strip()
            tim = tim.text.strip(' • ')
            url = self.host + i.get('href')

            img = i.find('script').text
            img = re.findall("(http.+?)'", img)[0]
            self.img_down.add(img)

            data.append(dict(tim=tim, url=url, img=f"http://192.168.1.7:5000/resources/imgs{parse.urlparse(img).path}", tit=tit))
        if txt and len(data) > 0:
            self.cache.set(self.host + path, txt)
        return data


if '__main__' == __name__:
    try:
        t = Gua01()

        print(t.nav())
        # print(len(t.list('/')))
        # print(t.list('/page/1'))
    finally:
        ChromeDriverService.close_driver()
        ChromeDriverService.close_driver('Gua01ImgDecry')
